package com.ruoyi.lvlian.service.impl;

import java.util.*;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.OrderTrackInfo;
import com.ruoyi.lvlian.dto.OrderInfoDto;
import com.ruoyi.lvlian.util.OrderNumberGenerator;
import com.ruoyi.lvlian.vo.OrderInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.lvlian.mapper.OrderInfoMapper;
import com.ruoyi.lvlian.domain.OrderInfo;
import com.ruoyi.lvlian.service.IOrderInfoService;

/**
 * 跟单信息Service业务层处理
 *
 * @author liyuxi
 * @date 2024-06-06
 */
@Service
public class OrderInfoServiceImpl implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    /**
     * 查询跟单信息
     *
     * @param id 跟单信息主键
     * @return 跟单信息
     */
    @Override
    public OrderInfoVo selectOrderInfoById(String id) {
        return orderInfoMapper.selectOrderInfoById(id);
    }

    /**
     * 查询跟单信息列表
     *
     * @param orderInfo 跟单信息
     * @return 跟单信息
     */
    @Override
    public List<OrderInfoVo> selectOrderInfoList(OrderInfoDto orderInfo) {
//        if (StringUtils.isNotEmpty( orderInfo.getPhone())) {
//            orderInfo.setBusinessUserId(MD5Utils.md5(orderInfo.getPhone()));
//        }
        List<OrderInfoVo> orderInfos = orderInfoMapper.selectOrderInfoList(orderInfo);


        // 设置默认值
        String defaultName = "默认名称"; // 替换为你的默认值
        for (OrderInfo info : orderInfos) {
            if (info.getSellerCompanyName() == null || info.getSellerCompanyName().isEmpty()) {
                info.setSellerCompanyName("发货方" + info.getSellerPhone());
            }
            if (info.getBusinessUserCompanyName() == null || info.getBusinessUserCompanyName().isEmpty()) {
                info.setBusinessUserCompanyName("业务方" + info.getBusinessUserPhone());
            }

            if (info.getBusinessUserName() == null || info.getBusinessUserName().isEmpty()) {
                info.setBusinessUserName("业务方" + info.getBusinessUserPhone());
            }
        }


        return orderInfos;
    }

    /**
     * 新增跟单信息
     *
     * @param orderInfo 跟单信息
     * @return 结果
     */
    @Override
    public String insertOrderInfo(OrderInfo orderInfo) {
        if (StringUtils.isEmpty(orderInfo.getOrderNum())) {
            orderInfo.setOrderNum(OrderNumberGenerator.generateOrderNumber());
        }

        orderInfo.setId(MD5Utils.md5(orderInfo.getOrderNum()));
        orderInfo.setCreateUser(SecurityUtils.getUsername());
        orderInfo.setCreateDate(DateUtils.getCurrentTime());
//        if (orderInfo.getBusinessUserStatus() == null || !"checkdeliveryfinishstart".contains(orderInfo.getBusinessUserStatus())) {
//            orderInfo.setBusinessUserStatus("check");
//        }

        orderInfoMapper.insertOrderInfo(orderInfo);
        return orderInfo.getId();
    }

    /**
     * 修改跟单信息
     *
     * @param orderInfo 跟单信息
     * @return 结果
     */
    @Override
    public String updateOrderInfo(OrderInfo orderInfo) {
        if(StringUtils.isEmpty( orderInfo.getCategory())){
            orderInfo.setCategory("采购跟单");
        }
        if (StringUtils.isEmpty( orderInfo.getId()) &&   StringUtils.isNotEmpty(orderInfo.getOrderNum()) ) {
            orderInfo.setId(MD5Utils.md5(orderInfo.getOrderNum()));
        }
        if (orderInfo.getBusinessUserStatus() == 1) {
            orderInfo.setBusinessUserStartTime(DateUtils.getCurrentTime());
        }
        int updateResult = orderInfoMapper.updateOrderInfo(orderInfo);


        if (0 == updateResult) {
            String result = this.insertOrderInfo(orderInfo);
            orderInfo.setId(result);
        }

//        保存轨迹状态
//        if (StringUtils.isNotEmpty(orderInfo.getStandardAddress())) {
            if (orderInfo.getBusinessUserStatus() > 0) {
                OrderTrackInfo orderTrackInfo = new OrderTrackInfo();
                orderTrackInfo.setCreateDate(DateUtils.getCurrentTime());
                orderTrackInfo.setStatusEn(orderInfo.getBusinessUserStatus());
                orderTrackInfo.setStandardAddress(orderInfo.getStandardAddress());
                orderTrackInfo.setOrderId(orderInfo.getId());
                orderTrackInfo.setId(MD5Utils.md5(orderInfo.getId() + orderInfo.getBusinessUserStatus()));
                orderTrackInfo.setCategory("bussinessUser");
                orderTrackInfo.setCreateUser(SecurityUtils.getUsername());
                orderTrackInfo.setCreateDate(DateUtils.getCurrentTime());

//                先检查是否存在
                boolean orderTrackInfoExist = orderInfoMapper.findOrderTrackInfoExist(orderTrackInfo.getId());
                if (!orderTrackInfoExist) {
                    orderInfoMapper.insertOrderTrackInfo(orderTrackInfo);
                }
            }

//        }


        return orderInfo.getId();
    }

    /**
     * 批量删除跟单信息
     *
     * @param ids 需要删除的跟单信息主键
     * @return 结果
     */
    @Override
    public int deleteOrderInfoByIds(String[] ids) {
        return orderInfoMapper.deleteOrderInfoByIds(ids);
    }

    /**
     * 删除跟单信息信息
     *
     * @param id 跟单信息主键
     * @return 结果
     */
    @Override
    public int deleteOrderInfoById(String id) {
        return orderInfoMapper.deleteOrderInfoById(id);
    }

    @Override
    public List<HashMap<String, Object>> countOrderByTimeRanges(OrderInfoDto orderInfoDto) {
        List<HashMap<String, Object>> hashMaps = orderInfoMapper.countOrderByTimeRanges(orderInfoDto);
        int all = 0;
        int notYet = 0;
        int finish = 0;
        int cancel = 0;

        Set<String> set = new HashSet<String>();
        for (HashMap<String, Object> map : hashMaps) {
            String cnName = String.valueOf(map.get("cnName"));
            int cnt = Integer.parseInt(String.valueOf(map.get("cnt")));
            if ("未完成".equalsIgnoreCase(cnName)) {
                notYet = notYet + cnt;
            }
            if ("已完成".equalsIgnoreCase(cnName)) {
                finish = finish + cnt;
            }
            if ("已取消".equalsIgnoreCase(cnName)) {
                cancel = cancel + cnt;
            }

            all = all + cnt;
        }


        List<HashMap<String, Object>> result = new ArrayList<>();


        HashMap<String, Object> nullMap1 = new HashMap<>();
        nullMap1.put("cnName", "未完成");
        nullMap1.put("cnt", notYet);
        nullMap1.put("businessUserStatus", "notYet");

        result.add(nullMap1);

        HashMap<String, Object> nullMap5 = new HashMap<>();
        nullMap5.put("cnName", "全部");
        nullMap5.put("cnt", all);
        nullMap5.put("businessUserStatus", "all");
        result.add(nullMap5);

        HashMap<String, Object> nullMap6 = new HashMap<>();
        nullMap6.put("cnName", "已完成");
        nullMap6.put("cnt", finish);
        nullMap6.put("businessUserStatus", 6);

        HashMap<String, Object> nullMap7 = new HashMap<>();
        nullMap7.put("cnName", "已取消");
        nullMap7.put("cnt", cancel);
        nullMap7.put("businessUserStatus", "cancel");

        result.add(nullMap6);
        result.add(nullMap7);

//输出排序
//        hashMaps.sort(Comparator.comparing(map -> (Integer) map.get("orderNum")));


        return result;
    }


    @Override
    public List<HashMap<String, Object>> countOrderByDriver(OrderInfoDto orderInfoDto) {
        List<HashMap<String, Object>> hashMaps = orderInfoMapper.countOrderByDriver(orderInfoDto);

        int all = 0;
        Set<String> set = new HashSet<String>();
        for (HashMap<String, Object> map : hashMaps) {
            String businessUserStatus = String.valueOf(map.get("cnName"));
            if("已取消".equalsIgnoreCase(businessUserStatus )){
                map.put("orderNum",4);
            }
            if("已完成".equalsIgnoreCase(businessUserStatus )){
                map.put("orderNum",3);
            }
            if("未完成".equalsIgnoreCase(businessUserStatus )){
                map.put("orderNum",2);
            }
            if("全部".equalsIgnoreCase(businessUserStatus )){
                map.put("orderNum",1);
            }

            int cnt = Integer.parseInt(String.valueOf(map.get("cnt")));
            all = all + cnt;
            set.add(businessUserStatus);
        }

        HashMap<String, Object> nullMap1 = new HashMap<>();
        nullMap1.put("cnName", "未完成");
        nullMap1.put("cnt", 0);
        nullMap1.put("businessUserStatus", "notYet");
        nullMap1.put("orderNum", 2);

        HashMap<String, Object> nullMap5 = new HashMap<>();

        HashMap<String, Object> nullMap6 = new HashMap<>();
        nullMap6.put("cnName", "已完成");
        nullMap6.put("cnt", 0);
        nullMap6.put("businessUserStatus", 6);
        nullMap6.put("orderNum",3);

        HashMap<String, Object> nullMap7 = new HashMap<>();
        nullMap7.put("cnName", "已取消");
        nullMap7.put("cnt", 0);
        nullMap7.put("businessUserStatus", 10);
        nullMap7.put("orderNum", 4);

        if (!set.contains("已完成")) {
            hashMaps.add(nullMap6);
        }
        if (!set.contains("未完成")) {
            hashMaps.add(nullMap1);
        }
        if (!set.contains("已取消")) {
            hashMaps.add(nullMap7);
        }

        nullMap5.put("cnName", "全部");
        nullMap5.put("cnt", all);
        nullMap5.put("businessUserStatus", "all");
        nullMap5.put("orderNum", 1);
        hashMaps.add(nullMap5);

        hashMaps.sort(Comparator.comparing(map -> (Integer) map.get("orderNum")));
        return hashMaps;
    }

    @Override
    public List<OrderInfoVo> queryOrderInfoByUserPhone(OrderInfoDto orderInfoDto) {

        List<OrderInfoVo> list = orderInfoMapper.queryOrderInfoByUserPhone1(orderInfoDto);
        for (OrderInfoVo vo : list) {
            if (vo.getDriverStartTime() != null && DateUtils.isValidDateTime(vo.getDriverStartTime())) {
                vo.setCloseTime(System.currentTimeMillis() - DateUtils.strToLong(vo.getDriverStartTime()));
                vo.setUsedTime((System.currentTimeMillis() - DateUtils.strToLong(vo.getDriverStartTime())) / 1000);
            }
            if (vo.getDriverStartTime() != null && DateUtils.isValidDateTime(vo.getDriverStartTime()) && vo.getDriverEndTime() != null && DateUtils.isValidDateTime(vo.getDriverEndTime())) {
                vo.setCloseTime(DateUtils.strToLong(vo.getDriverEndTime()) - DateUtils.strToLong(vo.getDriverStartTime()));
                vo.setUsedTime((DateUtils.strToLong(vo.getDriverEndTime()) - DateUtils.strToLong(vo.getDriverStartTime())) / 1000);
            }

        }

        return list;
    }

    @Override
    public int queryOrderCnt(String businessUserPhone, String driverPhone, String period) {
        return orderInfoMapper.queryOrderCnt(businessUserPhone, driverPhone, period);
    }

    @Override
    public List<OrderInfoVo> queryOrderInfoByDriverPhone(OrderInfoDto orderInfoDto) {
        List<OrderInfoVo> list = orderInfoMapper.queryOrderInfoByDriverPhone(orderInfoDto);
        for (OrderInfoVo vo : list) {
            if (vo.getDriverStartTime() != null && DateUtils.isValidDateTime(vo.getDriverStartTime())) {
                vo.setCloseTime(System.currentTimeMillis() - DateUtils.strToLong(vo.getDriverStartTime()));
                vo.setUsedTime((System.currentTimeMillis() - DateUtils.strToLong(vo.getDriverStartTime())) / 1000);
            }
            if (vo.getDriverStartTime() != null && DateUtils.isValidDateTime(vo.getDriverStartTime()) && vo.getDriverEndTime() != null && DateUtils.isValidDateTime(vo.getDriverEndTime())) {
                vo.setCloseTime(DateUtils.strToLong(vo.getDriverEndTime()) - DateUtils.strToLong(vo.getDriverStartTime()));
                vo.setUsedTime((DateUtils.strToLong(vo.getDriverEndTime()) - DateUtils.strToLong(vo.getDriverStartTime())) / 1000);
            }

        }
        return list;
    }


    @Override
    public List<OrderTrackInfo> queryOrderTrackInfoList(String orderId, String category) {
        List<OrderTrackInfo> orderTrackInfos = orderInfoMapper.queryOrderTrackInfoList(orderId, category);
        for(OrderTrackInfo vo: orderTrackInfos){
            switch (vo.getStatusEn()) {
                case 1:
                    vo.setStatusCn("跟车方已请求");
                    break;
                case 2:
                    vo.setStatusCn("司机已授权");
                    break;
                case 3:
                    vo.setStatusCn("跟车方已发起");
                    break;
                case 4:
                    vo.setStatusCn("司机运输中");
                    break;
                case 5:
                    vo.setStatusCn("司机已交货");
                    break;
                case 6:
                    vo.setStatusCn("跟车方已查收");
                    break;
                default:
                    vo.setStatusCn("跟车方已请求");
                    break;
            }
        }
        return orderTrackInfos ;
    }

    @Override
    public boolean validateVehicleOrderPermission(String driverPhone, String plateNo) {
        return orderInfoMapper.validateVehicleOrderPermission(driverPhone, plateNo);
    }
}
